from django.shortcuts import render
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.authorization import MyAuth
from cart import models,cartser

class AddCart(APIView):
    #开启认证
    authentication_classes = [MyAuth]
    def post(self, request):
        # Add item to cart
        #获取用户  course
        user=request.data.get("user",None)
        course=request.data.get("course",None)
        if not user or not course:
            return Response({"msg": "缺少参数"})
        #添加到购物车
        #判断购物车中是否已经存在该课程
        info=models.CartModel.objects.filter(user=user,course=course).first()
        if info:
            return Response({"msg":"购物车中已经存在该课程"})
        #不存在则添加
        ser=cartser.CartSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg":"添加成功"})
        return Response({"msg":"添加失败","errors":ser.errors})

class CartList(APIView):
    authentication_classes = [MyAuth]
    def get(self,request):
        user=request.query_params.get('user',None)
        if not user:
            return Response({'error':'用户不能为空'})
        info=models.CartModel.objects.filter(user=user)
        ser=cartser.CarSer(info,many=True)
        return Response({"msg":"ok","data":ser.data})

class CartUpdate(APIView):
    authentication_classes = [MyAuth]
    def put(self,request):
        id=request.data.get('id',None)
        info = models.CartModel.objects.filter(id=id).first()
        info.is_select = not info.is_select
        info.save()
        return Response({"msg":"ok"})

class Cartall(APIView):
    authentication_classes = [MyAuth]
    def put(self,request):
        user=request.data.get('user',None)
        check=request.data.get('check',None)
        if check:
            models.CartModel.objects.filter(user=user).update(is_select=True)
        else:
            models.CartModel.objects.filter(user=user).update(is_select=False)
        return Response({"msg":"ok"})
class Cardelete(APIView):
    authentication_classes = [MyAuth]
    def delete(self, request):
        id = request.query_params.get('id', None)
        info = models.CartModel.objects.filter(id=id)
        info.delete()
        return Response({"msg": "ok"})

class CartSelect(APIView):
    def get(self,request):
        user=request.query_params.get("user")
        if not user:
            return Response("请传递user")
        cart_list=models.CartModel.objects.filter(user=user,is_select=True)
        ser=cartser.CarSer(cart_list,many=True)
        return Response({"data":ser.data,"msg":"ok"})

